<template>
	<view class="container bk-little-gray">
		<view class="step_one">
			<view class="lay-c-c mg-t-lg pd-v-md">
				<text class="title">第一步：场次设置</text>
			</view>
			<view class="popup_group">
				<view class="popup_group_item">
					<view class="popup_group_item_label">场数</view>
					<view class="popup_group_item_value"><input v-model="setFormData.roundNumber" type="number" maxlength="2"/></view>
				</view>
				<view class="popup_group_item">
					<view class="popup_group_item_label">分区数</view>
					<view class="popup_group_item_value"><input v-model="setFormData.partitionNumber" type="number" maxlength="2"/></view>
				</view>
				<view class="popup_group_item">
					<view class="popup_group_item_label">每区人数</view>
					<view class="popup_group_item_value"><input v-model="setFormData.partitionPersons" type="number" maxlength="4"/></view>
				</view>
				<!-- <view class="popup_group_item">
					<view class="popup_group_item_label">准备时长(分钟)</view>
					<view class="popup_group_item_value"><input v-model="setFormData.prepairMinutes" type="number" maxlength="4" placeholder="提前摇号时间"/></view>
				</view> -->
				<view class="popup_group_item">
					<view class="popup_group_item_label">排名方式</view>
					<radio-group @change="onRankTypeChange($event)" style="display: flex;">
						<label style="display: flex;">
							<view><radio value=0 :checked="0==setFormData.rankType" /></view>
							<view>倒积分制</view>
						</label>
						<label style="display: flex; margin-left: 20rpx;">
							<view><radio value=1 :checked="1==setFormData.rankType" /></view>
							<view>累积渔获</view>
						</label>
					</radio-group>
				</view>
				<view class="popup_group_item">
					<view class="popup_group_item_label">撤大边</view>
					<switch :checked="setFormData.bigsideEnable" color="#E93323" style="transform:scale(0.8)" @change="useBigside" />
				</view>
				<view class="popup_group_item">
					<view class="popup_group_item_label">比赛中是否公开成绩</view>
					<switch :checked="setFormData.openScore" color="#E93323" style="transform:scale(0.8)" @change="openScoreChange" />
				</view>
			</view>
			
			<view class="mg-b-md pd-md lay-c-c">
				<button class="btn flex1 bk-red white" @click="saveRounds">保存场次设置</button>
			</view>
			
			<block v-if="showStep2">
				<view>
					<view class="lay-c-c mg-t-lg pd-v-md">
						<text class="title">第二步：场次分区设置</text>
					</view>
					
					<block v-for="(oneRound, roundIdx) in setFormData.rounds" :key="roundIdx">
						<view style="margin-left: 20rpx; margin-bottom: -20rpx">
							<text class="title">第{{roundIdx+1}}场时间</text>
						</view>
						
						<view class="popup_group">
							<view class="popup_group_item">
								<view class="popup_group_item_label">准备时间(分钟)</view>
								<view class="popup_group_item_value">
									<input v-model="oneRound.prepair" type="number" maxlength="4"/>
								</view>
							</view>
							
							<view class="popup_group_item">
								<view class="popup_group_item_label">比赛时长(分钟)</view>
								<view class="popup_group_item_value">
									<input v-model="oneRound.matchTime" type="number" maxlength="4"/>
								</view>
							</view>
						</view>
						<!-- <view class="popup_group">
							<view class="popup_group_item">
								<view class="popup_group_item_label">开始时间</view>
								<view class="popup_group_item_value">
									<picker mode="time" :start="oneRound.startTime" :value="oneRound.startTime" @change="onRoundStartTimeChange($event, roundIdx)">
										<view class="uni-input">{{oneRound.startTime}}</view>
									</picker>
								</view>
							</view>
							
							<view class="popup_group_item">
								<view class="popup_group_item_label">结束时间</view>
								<view class="popup_group_item_value">
									<picker mode="time" :start="oneRound.startTime" :value="oneRound.endTime" @change="onRoundEndTimeChange($event, roundIdx)">
										<view class="uni-input">{{oneRound.endTime}}</view>
									</picker>
								</view>
							</view>
						</view> -->
					</block>
				</view>
				
				<block v-for="(partition, partitionIdx) in setFormData.partitions" :key="partitionIdx">
					<view style="margin-left: 20rpx; margin-bottom: -20rpx">
						<text class="title">分区{{partitionIdx+1}}设置</text>
					</view>
					<view class="popup_group">
						<view class="popup_group_item">
							<view class="popup_group_item_label">成绩类型</view>
							<radio-group @change="onScoreTypeChange($event, partitionIdx)" style="display: flex;">
								<label style="display: flex;">
									<view><radio value=0 :checked="0==partition.scoreType || 2==partition.scoreType" /></view>
									<view>按重量</view>
								</label>
								<label style="display: flex; margin-left: 20rpx;">
									<view><radio value=1 :checked="1==partition.scoreType" /></view>
									<view>按尾数</view>
								</label>
							</radio-group>
						</view>
						<view class="popup_group_item" v-if="0 == partition.scoreType || 2 == partition.scoreType">
						  <view class="popup_group_item_label">去皮模式</view>
						  <view class="popup_group_item_value">
								<label>
									<switch color="#f00" disabled @click="onChangeSkinMode($event, partitionIdx)" :checked="2 == partition.scoreType" />快速
								</label>
							</view>
						</view>
						<view class="popup_group_item" style="display: none;">
							<view class="popup_group_item_label">分区使用比赛钓塘数</view>
							<radio-group @change="onPartitionPondNumChange($event, partitionIdx)" style="display: flex;">
								<label style="display: flex;">
									<view><radio value=1 :checked="1==partition.usePondNum" /></view>
									<view>1</view>
								</label>
								<label style="display: flex; margin-left: 20rpx;">
									<view><radio value=2 :checked="2==partition.usePondNum" /></view>
									<view>2</view>
								</label>
								<label style="display: flex; margin-left: 20rpx;">
									<view><radio value=3 :checked="3==partition.usePondNum" /></view>
									<view>3</view>
								</label>
							</radio-group>
						</view>
						<block v-for="(pond, pondIdx) in partition.ponds" :key="pondIdx">
							<view class="popup_group_item">
								<view class="popup_group_item_label">选择比赛钓塘{{pondIdx+1}}</view>
								<view class="popup_group_item_value">
									<picker @change="pondPickerChange($event, partitionIdx, pondIdx)" :value="pond.pondIndex" :range="availablePonds" range-key="storeName">
										<view class="uni-input">{{availablePonds[pond.pondIndex].storeName}}</view>
									</picker>
								</view>
							</view>
							<view class="popup_group_item bk-white-gray">
								<view class="popup_group_item_label">钓位</view>
								<view class="flex">
									<picker @change="pondSeatPickerChange($event, partitionIdx, pondIdx, pond.pondIndex, 0)" :value="pond.fromSeatIdx" :range="availablePonds[pond.pondIndex].seatNos" style="width:100rpx; background-color: white;">
										<view class="uni-input" style="text-align: center;">{{availablePonds[pond.pondIndex].seatNos[pond.fromSeatIdx]}}</view>
									</picker>
									~
									<picker @change="pondSeatPickerChange($event, partitionIdx, pondIdx, pond.pondIndex, 1)" :value="pond.toSeatIdx" :range="availablePonds[pond.pondIndex].seatNos" style="width:100rpx; background-color: white;">
										<view class="uni-input" style="text-align: center;">{{availablePonds[pond.pondIndex].seatNos[pond.toSeatIdx]}}</view>
									</picker>
								</view>
							</view>
							<view class="popup_group_item bk-white-gray">
								<view class="popup_group_item_label">钓位间隔</view>
								<view class="flex">
									每
									<input v-model="pond.perPersons" type="number" maxlength="2" style="width:60rpx;" class="mg-h-md solid radius line-gray"/>
									个空
									<input v-model="pond.perPersonsFree" type="number" maxlength="2" style="width:60rpx"  class="mg-h-md solid radius line-gray"/>
									个
								</view>
							</view>
							<view class="popup_group_item bk-white-gray">
								<view class="popup_group_item_label">大边位</view>
								<view class="popup_group_item_value"><input v-model="pond.bigsideSeats" type="text" maxlength="255" value="" placeholder="用逗号分隔" /></view>
							</view>
						</block>
					</view>
				</block>
				
				<view class="mg-b-md pd-md lay-c-c">
					<button class="btn flex1 bk-red white" @click="savePartitions">保存场次时间和分区设置</button>
				</view>
			</block>
		</view>
	</view>
</template>

<script>
const app = getApp();
import { navigateTo, serialize, setStorage, getStorage, removeStorage, Loading, hideLoading, Modal } from '../../libs/uniApi.js';

import store from '@/store';
import {genDefaultPartition, correctSeats, MyTip} from '../../components/ssty/common.js';

import {queryForEditRound, saveForEditRound} from '@/api/fsh.js'

export default {
	data() {
		
		return {
			showStep2: false,
			
			setFormData: {
				roundNumber: 1,
				partitionNumber: 1,
				partitionPersons: '',
				prepairMinutes: 0,
				rankType: 0,
				bigsideEnable: 1,
				openScore: 0,

				rounds: [{
					startTime: '08:00',
					endTime: '12:00',
				}],
				
				// 分区设置
				partitions: [{
					scoreType: 0, 			// 成绩类型：0-按重量，1-按尾数
					usePondNum: 1,			// 分区使用比赛钓塘数
					ponds: [this.genDefaultPartiPond()]
				}],
			},
			
			
			// 钓塘列表
			availablePonds: [{
				prodId: 1,
				storeName: 'A',
				seatNos: [1,2,4], // 钓位列表，不含禁用的
			}],
		};
	},
	onLoad(opt) {
		
		this.merId = opt.merId;
		this.product_id = opt.prodId;
		this.raceId = opt.raceId;

		// 查询钓塘列表
		queryForEditRound(this.merId, this.raceId).then(res=>{
			res.entity.goods.forEach(a=>{
				a.seatNos = a.seatNos.split(',');
			})
			this.availablePonds = [{prodId:0, storeName:'请选择比赛要使用的钓塘'}, ...res.entity.goods];
			
			this.setFormData.roundNumber = res.entity.race.round_number;
			this.setFormData.partitionNumber = res.entity.race.partition_number;
			this.setFormData.partitionPersons = parseInt(res.entity.race.partition_persons);
			this.setFormData.prepairMinutes = res.entity.race.prepair_minutes == null ? 0 : res.entity.race.prepair_minutes;
			this.setFormData.rankType = res.entity.race.rank_type == null ? 0 : res.entity.race.rank_type;
			this.setFormData.bigsideEnable = res.entity.race.bigside_enable == null ? 0 : res.entity.race.bigside_enable;
			this.setFormData.openScore = res.entity.race.open_score == null ? 0 : res.entity.race.open_score;
			this.setFormData.race_date = res.entity.race.race_date;
			
			if(res.entity.race.partitions) { 
				this.setFormData.rounds = JSON.parse(res.entity.race.rounds);
				this.setFormData.partitions = JSON.parse(res.entity.race.partitions);
				
				// 重新计划pondIndex，因为钓塘可能会增删
				let calcPondIdx = (prodId)=>{
					for(let k = 0; k < this.availablePonds.length; k++) {
						if(parseInt(this.availablePonds[k].prodId) == parseInt(prodId)) {
							return k;
						}
					}
					return 0;
				}
				this.setFormData.partitions.forEach(parti=>{
					parti.ponds.forEach(pond=>{
						pond.pondIndex = calcPondIdx(pond.prodId);
						
						pond.fromSeatIdx = this.availablePonds[pond.pondIndex].seatNos.indexOf(pond.fromSeatNo);
						if(pond.fromSeatIdx < 0)
							pond.fromSeatIdx = 0;
						pond.toSeatIdx = this.availablePonds[pond.pondIndex].seatNos.indexOf(pond.toSeatNo);
						if(pond.toSeatIdx < 0)
							pond.toSeatIdx = 0;
					})
				})
				
				this.showStep2 = true;
			}
			else { // 初始没配置，采用默认值
				this.resetPartitions();
				this.resetRounds();
			}
			
			console.log("queryForEditRound success, availablePonds:", this.availablePonds, "setFormData:", this.setFormData);
		}).catch(e=>{
			console.error(e);
			MyTip("查询失败，请稍后重试");
		});
			
		// this.$debugAlert('pages/product/addGoods/raceIndex>productDetail', 
		// 'app/common/repositories/store/product/ProductRepository.php>getAdminOneProduct',
		// 'cmh.ssty.controller.MlsrvController>queryYpProd');
	},
	onShow() {
	},
	
	watch: {
		'setFormData.partitionNumber'(newVal, oldVal) {
			console.log("partitionNumber change: ", newVal, oldVal)
			if(newVal != oldVal && newVal != this.setFormData.partitions.length) {
				this.resetPartitions();
			}
		},
		
		'setFormData.roundNumber'(newVal, oldVal) {
			console.log("roundNumber change: ", newVal, oldVal)
			if(newVal != oldVal && newVal != this.setFormData.rounds.length) {
				this.resetRounds();
			}
		}
	},
	methods: {
		genDefaultPartiPond() {
			return {
				id: '',				// 钓塘id
				pondIndex: 0,		// 钓塘在availablePonds中的索引（主要给picker用）
				prodId: '',			// 钓塘商品id
				pondProdName: '', 	// 钓塘名称
				
				fromSeatNo: 1,		// 开始钓位
				toSeatNo: 2,		// 结束钓位
				
				// 每隔perPersons个空perPersonsFree个
				perPersons: 1, 
				perPersonsFree: 0,
				
				bigsideSeats: '', 	// 大边位，用逗号分隔
				
				fromSeatIdx: 0,
				toSeatIdx: 1,
			}
		},
		
		resetPartitions() {
			if(this.setFormData.partitions.length > this.setFormData.partitionNumber)
				this.setFormData.partitions.splice(this.setFormData.partitionNumber, this.setFormData.partitions.length-this.setFormData.partitionNumber);
			else if(this.setFormData.partitions.length < this.setFormData.partitionNumber) {
				while(this.setFormData.partitions.length < this.setFormData.partitionNumber) {
					this.setFormData.partitions.push({
						scoreType: 0, 			// 成绩类型：0-按重量，1-按尾数
						usePondNum: 1,			// 分区使用比赛钓塘数
						
						// 比赛钓塘
						ponds: [this.genDefaultPartiPond()]
					});
				}
			}
			
			console.log("resetPartitions: ", this.setFormData.partitions)
		},
		
		resetRounds() {
			if(this.setFormData.rounds.length > this.setFormData.roundNumber)
				this.setFormData.rounds.splice(this.setFormData.roundNumber, this.setFormData.rounds.length-this.setFormData.roundNumber);
			else if(this.setFormData.rounds.length < this.setFormData.roundNumber) {	
				while(this.setFormData.rounds.length < this.setFormData.roundNumber) {
					this.setFormData.rounds.push({
						// 场次时间
						startTime: '08:00',
						endTime: '12:00'
					});
				}
			}
			
			console.log("resetRounds: ", this.setFormData.rounds)
		},
		
		onChangeSkinMode(e, partitionIdx) {
			let that = this;
			if(that.setFormData.partitions[partitionIdx].scoreType!=2){
				uni.showModal({
					title: '注意',
					content: '此模式设计为鱼情非常火爆的竞赛钓塘使用，每分钟上鱼小于3杆的钓塘不建议使用。确认选用此模式？',
					success: (res)=> {
						if (res.confirm) {
							that.setFormData.partitions[partitionIdx].scoreType = 2;
						} else if (res.cancel) {
							that.setFormData.partitions[partitionIdx].scoreType = 0;
						}
					}
				});
			}else{
				that.setFormData.partitions[partitionIdx].scoreType = 0;
			}
		},
		
		onRankTypeChange(e) {
			let v = parseInt(e.detail.value);
			this.setFormData.rankType = v;
		},
		
		onScoreTypeChange(e, partitionIdx) {
			let v = parseInt(e.detail.value);
			this.setFormData.partitions[partitionIdx].scoreType = v;
		},
		
		onPartitionPondNumChange(e, partitionIdx) {
			let usePondNum = this.setFormData.partitions[partitionIdx].usePondNum = parseInt(e.detail.value);
			let ponds = this.setFormData.partitions[partitionIdx].ponds;

			if(ponds.length > usePondNum)
				ponds.splice(usePondNum, ponds.length - usePondNum);
			else if(ponds.length < usePondNum) {
				while(ponds.length < usePondNum) {
					ponds.push(this.genDefaultPartiPond());
				}
			}
		},
		
		useBigside(e) {
			this.setFormData.bigsideEnable = e.detail.value ? 1: 0;
		},
		
		openScoreChange(e) {
			this.setFormData.openScore = e.detail.value ? 1: 0;
		},
		
		pondPickerChange(e, partitionIdx, partiPondIdx) {
			let pondIndex = parseInt(e.target.value);
			this.setFormData.partitions[partitionIdx].ponds[partiPondIdx].pondIndex = pondIndex;
			this.setFormData.partitions[partitionIdx].ponds[partiPondIdx].id = this.availablePonds[pondIndex].id;
			this.setFormData.partitions[partitionIdx].ponds[partiPondIdx].prodId = this.availablePonds[pondIndex].prodId;
			this.setFormData.partitions[partitionIdx].ponds[partiPondIdx].pondProdName = this.availablePonds[pondIndex].storeName;
			console.log("pondPickerChange: ", partitionIdx, this.setFormData.partitions)
		},
		
		pondSeatPickerChange(e, partitionIdx, partiPondIdx, pondIdx, type) {
			let idx = parseInt(e.target.value);
			this.setFormData.partitions[partitionIdx].ponds[partiPondIdx][type==0?'fromSeatIdx':'toSeatIdx'] = idx;
			this.setFormData.partitions[partitionIdx].ponds[partiPondIdx][type==0?'fromSeatNo':'toSeatNo'] = this.availablePonds[pondIdx].seatNos[idx];
			this.setFormData = JSON.parse(JSON.stringify(this.setFormData));
			console.log("pondSeatPickerChange: ", partitionIdx, partiPondIdx, type, idx, this.setFormData.partitions[partitionIdx].ponds[partiPondIdx]);
		},
			
		onRoundStartTimeChange(e, roundIdx) {
			this.setFormData.rounds[roundIdx].startTime = e.detail.value
		},
		
		onRoundEndTimeChange(e, roundIdx) {
			this.setFormData.rounds[roundIdx].endTime = e.detail.value
		},
		
		
		saveRounds() {
			this.doSubmit(1);
		},
		
		savePartitions() {
			this.doSubmit(2);
		},
		
		tip(title) {
			MyTip(title, 2500);
		},
		
		doSubmit(currStep) {
			let postData;
			
			if(currStep == 1) {
				if(!this.setFormData.roundNumber) {
					this.tip("请指定有效场数");
					return;
				}
				if(!this.setFormData.partitionNumber) {
					this.tip("请指定有效分区数");
					return;
				}
				if(!this.setFormData.partitionPersons) {
					this.tip("请指定有效每区人数");
					return;
				}
				if(!this.setFormData.prepairMinutes) {
					this.setFormData.prepairMinutes = 0;
					// this.tip("请指定有效准备时长");
					// return;
				}
				
				postData = {
					step: currStep,
					raceId: this.raceId,
					...this.setFormData
				};
				console.log(this.setFormData)
			}
			else {
				// for(let i = 0; i < this.setFormData.rounds.length; i++) {
				// 	let round = this.setFormData.rounds[i];
				// 	if(round.endTime <= round.startTime) {
				// 		this.tip("第"+(i+1)+"场结束时间小于或等于开始时间，不合理！");
				// 		return;
				// 	}
				// 	if(i > 0 && round.startTime <= this.setFormData.rounds[i-1].endTime) {
				// 		this.tip("第"+(i+1)+"场开始时间小于或等于上一场结束时间，不合理！");
				// 		return;
				// 	}
				// }
				
				for(let i = 0; i < this.setFormData.partitions.length; i++) {
					let parti = this.setFormData.partitions[i];
					if(parti.usePondNum != parti.ponds.length) {
						this.tip("第"+(i+1)+"区配置钓塘数量无效！");
						return;
					}
					if(parti.usePondNum >= this.availablePonds.length) {
						this.tip("第"+(i+1)+"区配置钓塘数量超过实际钓塘数量！");
						return;
					}
					
					let partiActualSeatCnt = 0; // 分区的实际有效钓位
					
					for(let j = 0; j < parti.ponds.length; j++) {
						let pond = parti.ponds[j];
						if(!pond.prodId || !pond.pondProdName) {
							this.tip("第"+(i+1)+"区配置的第"+(j+1)+"个钓塘无效！");
							return;
						}
						
						let fromSeatNo = parseInt(pond.fromSeatNo);
						let toSeatNo = parseInt(pond.toSeatNo);
						if(!fromSeatNo || !toSeatNo || toSeatNo < fromSeatNo) {
							this.tip("第"+(i+1)+"区第"+(j+1)+"个钓塘配置的钓位无效！");
							return;
						}
						
						// 不能做如下校验，因为配置钓塘时，钓位号可能>钓位数
						//if(toSeatNo > parseInt(this.availablePonds[pond.pondIndex].seatCount)) {
						//	this.tip("第"+(i+1)+"区第"+(j+1)+"个钓塘配置的钓位超过该塘实际钓位数！");
						//	return;
						//}
						
						let perPersons = parti.perPersons ? parseInt(parti.perPersons) : 0;
						let perPersonsFree = parti.perPersonsFree ? parseInt(parti.perPersonsFree) : 0;
						if(perPersonsFree > 0) {
							if(perPersons < 1) {
								this.tip("第"+(i+1)+"区钓位间隔配置无效！");
								return;
							}

							let seatCnt = toSeatNo - fromSeatNo + 1;
							let freeCnt = parseInt(seatCnt / (perPersons + perPersonsFree)) * perPersonsFree;
							partiActualSeatCnt += seatCnt - freeCnt;
						}
						else {
							partiActualSeatCnt += toSeatNo - fromSeatNo + 1;
						}
						
						// 检查钓位配置重叠情况
						for(let ii = 0; ii < this.setFormData.partitions.length; ii++) {
							let _parti = this.setFormData.partitions[ii];
							for(let jj = 0; jj < _parti.ponds.length; jj++) {
								if(ii == i && jj == j)
									continue;
								let _pond = _parti.ponds[jj];
								if(pond.pondProdName == _pond.pondProdName) {
									let _fromSeatNo = parseInt(_pond.fromSeatNo);
									let _toSeatNo = parseInt(_pond.toSeatNo);
									if(_fromSeatNo >= fromSeatNo && _fromSeatNo <= toSeatNo) {
										this.tip(`第${i+1}区${j+1}个钓塘钓位和第${ii+1}区${jj+1}个钓塘的钓位配置有重叠情况！`);
										return;
									}
								}
							}
						}
					}
					
					if(partiActualSeatCnt < parseInt(this.setFormData.partitionPersons)) {
						this.tip("第"+(i+1)+"区的实际有效钓位小于分区人数！");
						return;
					}
				}
				
				postData = {
					step: currStep,
					raceId: this.raceId,
					rounds: JSON.stringify(this.setFormData.rounds),
					partitions: JSON.stringify(this.setFormData.partitions),
					prepairMinutes: this.setFormData.prepairMinutes,
					
					firstStartTime: this.setFormData.race_date + " " + this.setFormData.rounds[0].startTime,
					lastEndTime: this.setFormData.race_date + " " + this.setFormData.rounds[this.setFormData.rounds.length-1].endTime,
					...this.setFormData
				};
			}
			
			uni.showLoading({
				title: '保存中...'
			});
			console.log("postData",postData)
			saveForEditRound(this.raceId, postData)
			.then(res => {
				hideLoading()
				
				console.log("race_manage_edit_round, saveForEditRound success");
				this.step = currStep + 1;
				if(currStep == 1)
					this.showStep2 = true;
				else if(currStep == 2) {
					Modal('保存成功', '', {
						showCancel: false
					}).then(() => {
						uni.navigateBack();
					})
				}
				else {
					MyTip('保存成功');
				}
			})
			.catch(errMsg => {
				uni.hideLoading();
				console.log("race_manage_edit_round, saveForEditRound fail", errMsg);
				MyTip(errMsg.msg);
			});
		},
	}
};
</script>

<style lang="scss" scoped>
@import './scss/index.scss';

@import "@/leui.scss";

</style>
